package seqlist.stack_queue;

import java.util.Arrays;
import java.util.NoSuchElementException;

/**
 * @author yuisama
 * @date 2023/03/21 19:08
 **/
public class MyStack<E> {
    private Object[] data;
    // 当前栈中有效元素的个数
    private int size;
    public MyStack() {
        this(10);
    }
    public MyStack(int capacity) {
        this.data = new Object[capacity];
    }
    // 入栈
    public void push(E val) {
        data[size ++] = val;
        if (size == data.length) {
            data = Arrays.copyOf(data,
                    data.length << 1);
        }
    }
    // 出栈
    public E pop() {
        if (isEmpty()) {
            throw new NoSuchElementException("stack is empty" +
                    "!cannot pop");
        }
        E val = (E) data[size - 1];
        size --;
        return val;
    }

    private boolean isEmpty() {
        return size == 0;
    }

    // 返回栈顶元素
    public E peek() {
        if (isEmpty()) {
            throw new NoSuchElementException("stack is empty" +
                    "cannot peek!");
        }
        return (E) data[size - 1];
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("bottom [");
        for (int i = 0; i < size; i++) {
            sb.append(data[i]);
            if (i < size - 1) {
                sb.append(", ");
            }
        }
        sb.append("] top");
        return sb.toString();
    }
}